package com.mcxx.modules.extremepoverty.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mcxx.common.exception.BizException;
import com.mcxx.constant.DictConstant;
import com.mcxx.convert.ApplyConvert;
import com.mcxx.modules.extremepoverty.service.ExSalvationApplyService;
import com.mcxx.modules.minimumliving.service.FiscalAbutmentService;
import com.mcxx.modules.base.service.read.AreaReadService;
import com.mcxx.modules.base.service.read.BankMappingReadService;
import com.mcxx.modules.base.service.read.DictionaryReadService;
import com.mcxx.modules.base.service.read.RuleEngineReadService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.miniSalvation.check.service.read.CheckReadService;
import com.mcxx.modules.miniSalvation.family.dto.*;
import com.mcxx.modules.miniSalvation.family.entity.*;
import com.mcxx.modules.miniSalvation.family.service.read.*;
import com.mcxx.modules.miniSalvation.family.service.write.BankWriteService;
import com.mcxx.modules.miniSalvation.family.service.write.FamilyMainWriteService;
import com.mcxx.modules.miniSalvation.family.service.write.FamilyMemberWriteService;
import com.mcxx.modules.miniSalvation.family.service.write.MemberAssetsWriteService;
import com.mcxx.modules.miniSalvation.order.dto.OrderInHouseDTO;
import com.mcxx.modules.miniSalvation.order.dto.OrderStateVerifyDTO;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.service.read.BlacklistReadService;
import com.mcxx.modules.miniSalvation.order.service.read.OrderCertReadService;
import com.mcxx.modules.miniSalvation.order.service.read.OrderReadService;
import com.mcxx.modules.miniSalvation.order.service.write.InHouseWriteService;
import com.mcxx.modules.miniSalvation.order.service.write.OrderWriteService;
import com.mcxx.modules.miniSalvation.salary.service.read.FamilyMemberSalaryReadService;
import com.mcxx.modules.miniSalvation.salary.service.write.FamilySalaryWriteService;
import com.mcxx.util.CommonUtil;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import com.yinhai.ta404.core.utils.UUIDUtils;
import com.yinhai.ta404.module.dict.entity.TaDictPo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;


@Service("exSalvationApplyService")
@TaTransactional
public class ExSalvationApplyServiceImpl extends BaseService implements ExSalvationApplyService {

    @Autowired
    private FamilyMainWriteService familyMainWriteService;
    @Autowired
    private FamilyMemberReadService familyMemberReadService;
    @Autowired
    private FamilyMemberWriteService familyMemberWriteService;
    @Autowired
    private FamilyMemberSalaryReadService memberSalaryReadService;
    @Autowired
    private OrderWriteService orderWriteService;
    @Autowired
    private OrderReadService orderReadService;
    @Autowired
    private OrderCertReadService orderCertReadService;
    @Autowired
    private MemberAssetsWriteService memberAssetsWriteService;
    @Autowired
    private MemberAssetsReadService memberAssetsReadService;
    @Autowired
    private InHouseWriteService inHouseWriteService;
    @Autowired
    private RuleEngineReadService ruleEngineReadService;
    @Autowired
    private FileService fileService;
    @Autowired
    private FamilyMainReadService familyMainReadService;
    @Autowired
    private FamilySupportReadService familySupportReadService;
    @Autowired
    private MemberAssetsReadService memberAssetsReadServicel;
    @Autowired
    private DictionaryReadService dictionaryReadService;
    @Autowired
    private BlacklistReadService blacklistReadService;
    @Autowired
    private CheckReadService checkReadService;
    @Autowired
    private AreaReadService areaReadService;
    @Autowired
    private BankMappingReadService bankMappingReadService;
    @Autowired
    private BankWriteService bankWriteService;
    @Autowired
    private FiscalAbutmentService fiscalAbutmentService;
    @Autowired
    private FamilySalaryWriteService familySalaryWriteService;
    @Value("${society.template.dir:bakhtml}")
    private String backUpDir;
    @Value("${society.template.minifilename:minibackup.html}")
    private String backUpMiniFileName;
    @Value("${society.template.exfilename:exbackup.html}")
    private String backUpExFileName;
    private final  String separator = System.getProperty("file.separator");




    public ApplyRtnDTO saveSalvationRequest(ExtremePovertyApplyDTO applyDto, UserAccountVo accountVo){


        List<FamilyMemberEntity> memberLists = familyMemberReadService.listNormalMemberByFamilyId(applyDto.getFamilyId());
        if(CollectionUtils.isNotEmpty(memberLists)){
            List<String> list = new ArrayList<>();
            for(FamilyMemberEntity memberList : memberLists){
                list.add(memberList.getIdcard());
            }
            List<String> names = blacklistReadService.cntByIdcards(list);
            if(org.apache.commons.collections.CollectionUtils.isNotEmpty(names)){
                throw  new BizException("-1","当前家庭成员【" + String.join(",", names) + "】在黑名单中");
            }

        }

        if(CommonUtil.invalidArgs(applyDto.getOrderId())){

            if(Constant.DomesticRelation.ONESELF.equals(applyDto.getFamilyRelation())){
                applyDto.setName(applyDto.getApplyName());
                applyDto.setIdcard(applyDto.getApplyIdcard());
            }
        }else{


            FamilyMemberEntity masertInfo = familyMemberReadService.getMasertInfo(applyDto.getFamilyId());
            if(!CommonUtil.invalidArgs(masertInfo)){
                applyDto.setMemberId(masertInfo.getId());
                applyDto.setName(masertInfo.getName());
                applyDto.setIdcard(masertInfo.getIdcard());
            }
        }

        FamilyMainEntity familyMainEntity = ApplyConvert.convertToFamilyMainEntity(applyDto, accountVo);
        FamilyMemberEntity memberEntity = ApplyConvert.convertToFamilyMemberEntity(applyDto, accountVo);


        if (Constant.OrderType.NEW.equals(applyDto.getType())) {
            memberSalaryReadService.checkMemberIsSaved(applyDto.getOrderId(), memberEntity.getId(), DateUtil.getMonthString());
        }


        ApplyRtnDTO applyRtnDTO = familyMainWriteService.addFamilyAndMember4Apply(familyMainEntity, memberEntity, applyDto.getMemberOldState(), accountVo,applyDto.getType());


        OrderEntity orderEntity = this.saveOrder(applyDto, applyRtnDTO, accountVo);


        applyRtnDTO.setOrderId(orderEntity.getOrderId());
        applyRtnDTO.setStandType(applyDto.getStandType());
        applyRtnDTO.setOrderBizState(orderEntity.getBizState());
        return applyRtnDTO;
    }


    @Override
    public ApplyRtnDTO addSalvationRequest(ExtremePovertyApplyDTO applyDto, UserAccountVo accountVo) throws BizException {

        return this.saveSalvationRequest(applyDto, accountVo);
    }


    @Override
    public ApplyRtnDTO modifySalvationRequest(ExtremePovertyApplyDTO applyDto, UserAccountVo accountVo,String channel) throws BizException {

        this.isCanEditOrder(applyDto, accountVo);


        this.verifyFamilyMasterNum(applyDto.getFamilyId());

        this.verifyApplyMaster(applyDto);


        //this.verifyMemberAssets(applyDto.getOrderId());

        this.verifySupportAuthor(applyDto.getFamilyId(),applyDto.getOrderId());

        this.verifyCompleteMemberInfo(applyDto.getFamilyId());


        this.verifyCert(applyDto.getOrderId(), applyDto.getFamilyId(),channel);


        ApplyRtnDTO applyRtnDTO = this.saveSalvationRequest(applyDto, accountVo);


        String inHouseId = this.saveOrderInHouse(applyDto, accountVo);
        applyRtnDTO.setOrderInhouseId(inHouseId);

        this.updateBankPhone(applyDto,applyRtnDTO.getMemberId());
        return applyRtnDTO;
    }


    @Override
    public ApplyRtnDTO houseHoldCancelSave(ExtremePovertyApplyDTO applyDto, UserAccountVo accountVo) throws BizException {

        this.isCanEditOrder(applyDto, accountVo);


        this.verifyFamilyMasterNum(applyDto.getFamilyId());


        this.verifyApplyMaster(applyDto);

//        this.verifyMemberAssets(applyDto.getOrderId());

//        this.verifySupportAuthor(applyDto.getFamilyId(),applyDto.getOrderId());


        this.verifyCompleteMemberInfo(applyDto.getFamilyId());


//        this.verifyCert(applyDto.getOrderId(), applyDto.getFamilyId());


        ApplyRtnDTO applyRtnDTO = this.saveSalvationRequest(applyDto, accountVo);


        String inHouseId = this.saveOrderInHouse(applyDto, accountVo);
        applyRtnDTO.setOrderInhouseId(inHouseId);

        return applyRtnDTO;
    }

    public void isCanEditOrder(ExtremePovertyApplyDTO applyDto, UserAccountVo userAccountVo){

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(applyDto.getOrderId());

        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.ORDER_EDIT, orderStateVerifyDTO, userAccountVo);
    }


    public OrderEntity saveOrder(ExtremePovertyApplyDTO applyDto, ApplyRtnDTO applyRtnDTO, UserAccountVo accountVo){

        applyDto.setFamilyId(applyRtnDTO.getFamilyId());

        if(CommonUtil.invalidArgs(applyDto.getMemberId()) &&  Constant.DomesticRelation.ONESELF.equals(applyDto.getFamilyRelation()) ){
            applyDto.setMemberId(applyRtnDTO.getMemberId());
        }
        OrderEntity orderEntity = ApplyConvert.convertToOrderEntity(applyDto, accountVo);
        orderEntity.setBusinessType(Constant.BusinessCode.TEKUN);


        if (CommonUtil.invalidArgs(applyDto.getOrderId())) {

            orderEntity.setOrderId(IdUtil.simpleUUID());
            orderEntity.setState(Constant.BizState.SALVATION);
            orderEntity.setBizState(Constant.BizState.SALVATION);
            orderEntity.setWoaState(Constant.WOASTATE.UNPROCESSED);
            orderWriteService.insertIgnoreNull(orderEntity);
        } else {
            if(!CommonUtil.invalidArgs(applyDto.getOrderBizState())){
                orderEntity.setBizState(applyDto.getOrderBizState());
            }
            if(!CommonUtil.invalidArgs(applyDto.getOrderState())){
                orderEntity.setState(applyDto.getOrderState());
            }

            orderWriteService.updateIgnoreNull(orderEntity);
        }
        return orderEntity;
    }


    public String saveOrderInHouse(ExtremePovertyApplyDTO applyDto, UserAccountVo userAccountVo) {

        if(CommonUtil.invalidArgs(applyDto.getCheckPeople()) || CommonUtil.invalidArgs(applyDto.getCheckDate())
                || CommonUtil.invalidArgs(applyDto.getCheckContent())){

            return null;
        }


        OrderInHouseDTO inHouseDTO = ApplyConvert.convertToInhouseEntity(applyDto);


        if(CommonUtil.invalidArgs(inHouseDTO.getId())){
            inHouseWriteService.addInHouse(inHouseDTO, applyDto.getInhouseCertIdList(), userAccountVo);
        }else{
            inHouseWriteService.updateById(inHouseDTO, applyDto.getInhouseCertIdList(), userAccountVo);
        }

        return inHouseDTO.getId();
    }

    public void updateBankPhone(ExtremePovertyApplyDTO applyDTO,String memberId){
        if(Constant.DomesticRelation.ONESELF.equals(applyDTO.getFamilyRelation())&&StringUtils.isNotEmpty(memberId)){
            BankEntity entity = new BankEntity();
            entity.setFamilyId(applyDTO.getFamilyId());
            entity.setMemberId(memberId);
            entity.setAgentBankPhone(applyDTO.getPhone());
            bankWriteService.updateBankPhone(entity);
        }
    }

    @Override
    public ApplyRtnDTO tempSaveInHouse(ExtremePovertyApplyDTO applyDto, UserAccountVo accountVo, String channel) {

        this.isCanTempSaveInHouse(applyDto, accountVo);


        this.verifyFamilyMasterNum(applyDto.getFamilyId());


        //this.verifyMemberAssets(applyDto.getOrderId());


        this.verifyCompleteMemberInfo(applyDto.getFamilyId());


        this.verifyCert(applyDto.getOrderId(), applyDto.getFamilyId(),channel);



        ApplyRtnDTO applyRtnDTO = this.saveSalvationRequest(applyDto, accountVo);


        String inHouseId = this.saveOrderInHouse(applyDto, accountVo);
        applyRtnDTO.setOrderInhouseId(inHouseId);


        return applyRtnDTO;
    }


    public void isCanTempSaveInHouse(ExtremePovertyApplyDTO applyDto, UserAccountVo accountVo){


        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(applyDto.getOrderId());


        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.START_TOWN_IN_HOUSE, orderStateVerifyDTO, accountVo);


        applyDto.setOrderBizState(orderStateVerifyDTO.getNextBizState());
    }


    @Override
    public ApplyRtnDTO completeInHouse(ExtremePovertyApplyDTO applyDto, UserAccountVo accountVo, String channel) {

        this.isCanCompleteInHouse(applyDto, accountVo);


        this.verifyFamilyMasterNum(applyDto.getFamilyId());


        //this.verifyMemberAssets(applyDto.getOrderId());


        this.verifyCompleteMemberInfo(applyDto.getFamilyId());


        this.verifyOrderInHouse(applyDto);


        this.verifyCert(applyDto.getOrderId(), applyDto.getFamilyId(),channel);



        ApplyRtnDTO applyRtnDTO = this.saveSalvationRequest(applyDto, accountVo);


        String inHouseId = this.saveOrderInHouse(applyDto, accountVo);
        applyRtnDTO.setOrderInhouseId(inHouseId);


        return applyRtnDTO;
    }


    public void isCanCompleteInHouse(ExtremePovertyApplyDTO applyDto, UserAccountVo userAccountVo){


        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(applyDto.getOrderId());

        orderStateVerifyDTO.setNextCondition("1");


        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.COMPLETE_TOWN_IN_HOUSE, orderStateVerifyDTO, userAccountVo);


        applyDto.setOrderBizState(orderStateVerifyDTO.getNextBizState());
        applyDto.setOrderState(orderStateVerifyDTO.getNextState());
    }






    @Override
    public double saveMemberAssets(MemberAssetsEntity entity, UserAccountVo userAccountVo) {

        memberAssetsReadService.cntMemberAssetsNotProperty(entity);


        if(CommonUtil.invalidArgs(entity.getId())){
            memberAssetsWriteService.insertIgnoreNull(entity, userAccountVo);
        }else{
            memberAssetsWriteService.updateIgnoreNull(entity);
        }


        double familyRevenue = familyMemberWriteService.updateFamilyRevenue(entity);

        return familyRevenue;
    }


    @Override
    public double deleteMemberAssets(MemberAssetsEntity entity) {

        memberAssetsWriteService.deleteById(entity.getId());

        double familyRevenue = familyMemberWriteService.updateFamilyRevenue(entity);

        return familyRevenue;
    }








    public void verifyMemberAssets(String orderId){
        int rst = memberAssetsReadService.cntOrderAssets(orderId);
        if(rst <= 0){
            throw new BizException(FailureCode.ERR_20068);
        }
    }


    public void verifyFamilyMasterNum(String familyId){
        int rst = familyMemberReadService.cntFamilyMaster(familyId);
        if(rst > 1){
            throw new BizException(FailureCode.ERR_10080);
        }
        if(rst == 0){
            throw new BizException(FailureCode.ERR_10081);
        }
    }


    @Override
    public void verifyCompleteMemberInfo(String familyId){
        String rst = familyMemberReadService.cntCompleteInfoNum(familyId, Constant.BusinessCode.TEKUN);

        if(!CommonUtil.invalidArgs(rst)){
            throw new BizException(FailureCode.ERR_20067);
        }
    }


    public void verifyOrderInHouse(ExtremePovertyApplyDTO applyDto){

        if(CommonUtil.invalidArgs(CommonUtil.invalidArgs(applyDto.getCheckPeople()) || CommonUtil.invalidArgs(applyDto.getCheckDate())
                || CommonUtil.invalidArgs(applyDto.getCheckContent()))){
            throw new BizException(FailureCode.ERR_20014);
        }


        if(CollectionUtils.isNotEmpty(applyDto.getInhouseCertIdList())){

            return;
        }

        int rst = orderCertReadService.cntInhouseCertNum(applyDto.getOrderId(), applyDto.getOrderInhouseId());
        if(rst <= 0){
            throw new BizException("-1", "当前家庭没有上传【入户调查辅证材料】，请上传！");
        }
    }


    @Override
    public void verifyCert(String orderId, String familyId,String channel){

        int rst = familyMemberReadService.cntFamilyMember(familyId);
        if(rst<1){
            Map<String, Long>  cntMap = orderCertReadService.cntFamilyCertNum(orderId, familyId);

            if(cntMap.containsKey("familyRegisterNum") && cntMap.get("familyRegisterNum") <= 0){
                throw new BizException("-1", "当前家庭没有上传【户口本】资料，请上传！");
            }

            if(cntMap.containsKey("checkAuthorizationNum") && cntMap.get("checkAuthorizationNum") <= 0){
                throw new BizException("-1", "当前家庭没有上传【救助申请家庭经济状况核对授权书】，请上传！");
            }

            if(StringUtils.isBlank(channel) && cntMap.containsKey("checkfamilyIntegrityNum") && cntMap.get("checkfamilyIntegrityNum") <= 0){
                throw new BizException("-1", "当前家庭没有上传【救助申请家庭诚信承诺书】，请上传！");
            }

            List<String> memberIdcardNumMap = orderCertReadService.cntMemberIdcardNum(orderId, familyId);
            if(CollectionUtils.isNotEmpty(memberIdcardNumMap)){
                throw new BizException("-1", "当前成员【" + String.join(",", memberIdcardNumMap) + "】没有上传身份证，请先上传身份证");
            }
        }

        List<String> supportNoIdCardName = orderCertReadService.cntSupportIdCardNum(orderId, familyId);
        if(CollectionUtils.isNotEmpty(supportNoIdCardName)){
            throw new BizException("-1", "当前赡抚养人【" + String.join(",", supportNoIdCardName) + "】没有上传身份证，请先上传身份证");
        }
        int count = orderCertReadService.selectSupportAuthor(familyId,orderId);
        if(count>0){
            throw new BizException(FailureCode.ERR_20085);
        }
    }


    @Override
    public  List<String> verifyMemberAssetsList(Map<String, String> orderIdIdcardMap){

        List<String> orderIdList = new ArrayList<>(orderIdIdcardMap.keySet());

        List<MemberAssetsDTO> memberAssetsDTOList = memberAssetsReadService.cntOrderAssetsList(orderIdList);
        Map<String, Integer> memberAssetsNumMap = memberAssetsDTOList.stream().collect(Collectors.toMap(MemberAssetsDTO::getOrderId, MemberAssetsDTO::getAssetsNum));


        List<String> noExistsAssestsIdcard = new ArrayList<>();
        orderIdList.forEach(orderId->{
            if(!memberAssetsNumMap.containsKey(orderId) || memberAssetsNumMap.get(orderId) == 0){

                noExistsAssestsIdcard.add(orderIdIdcardMap.get(orderId));
            }
        });
        return noExistsAssestsIdcard;
    }


    @Override
    public List<String> verifyFamilyMasterNum(Map<String, String> familyIdIdcardMap){

        List<String> familyIdList =  new ArrayList<>(familyIdIdcardMap.keySet());

        List<String> masterNumOneList = familyMemberReadService.cntFamilyMasterErrorList(familyIdList);

        List<String> masterNumErrorIdcard = new ArrayList<>();
        masterNumOneList.forEach(familyId -> {
            masterNumErrorIdcard.add(familyIdIdcardMap.get(familyId));
        });
        return masterNumErrorIdcard;
    }



    @Override
    public List<String> verifyCompleteMemberInfo(Map<String, String> familyIdIdcardMap){

        List<String> familyIdList =  new ArrayList<>(familyIdIdcardMap.keySet());

        List<String> infoNoCompList = familyMemberReadService.cntCompleteInfoNumList(familyIdList);

        List<String> memberInfoNoCompleteIdcard = new ArrayList<>();
        infoNoCompList.forEach(familyId -> {
            memberInfoNoCompleteIdcard.add(familyIdIdcardMap.get(familyId));
        });
        return memberInfoNoCompleteIdcard;
    }


    public void verifyCertList(String orderId, String familyId){
        Map<String, Long>  cntMap = orderCertReadService.cntFamilyCertNum(orderId, familyId);

        if(cntMap.containsKey("familyRegisterNum") && cntMap.get("familyRegisterNum") <= 0){
            throw new BizException("-1", "当前家庭没有【上传户口本资料】，请上传！");
        }

        if(cntMap.containsKey("checkAuthorizationNum") && cntMap.get("checkAuthorizationNum") <= 0){
            throw new BizException("-1", "当前家庭没有上传【救助申请家庭经济状况核对授权书】，请上传！");
        }

        if(cntMap.containsKey("checkfamilyIntegrityNum") && cntMap.get("checkfamilyIntegrityNum") <= 0){
            throw new BizException("-1", "当前家庭没有上传【救助申请家庭诚信承诺书】，请上传！");
        }

        List<String> memberIdcardNumMap = orderCertReadService.cntMemberIdcardNum(orderId, familyId);
        if(CollectionUtils.isNotEmpty(memberIdcardNumMap)){
            throw new BizException("-1", "当前成员【" + String.join(",", memberIdcardNumMap) + "】没有上传身份证，请先上传身份证");
        }
    }






    @Override
    public String modifyFamilyHolder(String familyId, String idcard, UserAccountVo accountVo) {
        FamilyMemberEntity memberStat = familyMemberReadService.getMemberStateByCardId(idcard);
        if (Constant.PeopleState.NORMAL.equals(memberStat.getState())) {

            return memberStat.getFamilyId();
        }
        FamilyMainEntity familyEntity=new FamilyMainEntity();

        familyEntity.setId(Constant.getUUID());

        familyEntity.setFamilyNumber(1);

        familyEntity.setAreaCode(accountVo.getAreaCode());

        familyMainWriteService.addFamily(familyEntity);

        familyMemberWriteService.changeFamilyId(familyId,idcard,familyEntity.getId());

        return familyEntity.getId();
    }

    public void verifyApplyMaster(ExtremePovertyApplyDTO applyDto){
        String masterIdCard = familyMemberReadService.getMasterIdCardByFamilyId(applyDto.getFamilyId());

        if(StringUtils.isNotEmpty(masterIdCard) && masterIdCard.equals(applyDto.getApplyIdcard())&&!Constant.DomesticRelation.ONESELF.equals(applyDto.getFamilyRelation())){
            throw new BizException(FailureCode.ERR_20004);
        }

        if(Constant.DomesticRelation.ONESELF.equals(applyDto.getFamilyRelation())){
            if(StringUtils.isNotEmpty(masterIdCard) && !masterIdCard.equals(applyDto.getApplyIdcard())){
                throw new BizException(FailureCode.ERR_20004);
            }
        }
    }

    public void verifySupportAuthor(String familyId,String orderId){

        int counts = orderCertReadService.selectSupportInfo(familyId);
        if(counts>0){
            throw new BizException("-1","当前家庭有赡(抚扶)养人信息未完善，请完善后再继续操作");
        }
        int count = orderCertReadService.selectSupportAuthor(familyId,orderId);
        if(count>0){
            throw new BizException(FailureCode.ERR_20085);
        }
    }


//        if(CommonUtil.invalidArgs(applyDto.getOrderId())){

//            if(!CommonUtil.invalidArgs(applyDto.getAgentIdcard())&&applyDto.getAgentIdcard().equals(applyDto.getApplyIdcard())){




//            int count = familyMemberReadService.selectCountByIdcard(applyDto.getAgentIdcard(),applyDto.getFamilyId());






    @Override
    public String backupHtml(String orderId,String familyId,String businessCode) {


        this.verifyFamilyMasterNum(familyId);





        this.verifyCompleteMemberInfo(familyId);


        InputStream htmlInputStream = null;
        if(Constant.BusinessCode.DIBAO.equals(businessCode)){
            htmlInputStream = this.getClass().getResourceAsStream("/"+backUpDir+"/"+backUpMiniFileName);
        }else{
            htmlInputStream = this.getClass().getResourceAsStream("/"+backUpDir+"/"+backUpExFileName);
        }

        FamilyMainBackUpEntity mainEntity = familyMainReadService.selectBackUpInfo(orderId);

        List<FamilyMemberEntity> familyMemberEntities = familyMemberReadService.listNormalMemberByFamilyId(familyId);

        List<FamilySupportEntity> familySupportList = familySupportReadService.getFamilySupportList(familyId);

        List<MemberAssetsDTO> memberAssetsEntities = memberAssetsReadServicel.queryListByFamilyId(familyId, orderId, "");


        TaDictPo taDictPo = dictionaryReadService.getCodeCache(DictConstant.FM_RELATION,mainEntity.getRelation());
        mainEntity.setRelation(taDictPo.getLabel());

        taDictPo = dictionaryReadService.getCodeCache(DictConstant.CENSUS_TYPE,mainEntity.getCensusType());
        mainEntity.setCensusType(taDictPo.getLabel());

        taDictPo = dictionaryReadService.getCodeCache(DictConstant.POVERTY_FACTORS,mainEntity.getMainreson());
        mainEntity.setMainreson(taDictPo.getLabel());


        for(FamilyMemberEntity memberEntity:familyMemberEntities){

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.FM_RELATION,memberEntity.getFamilyRelation());
            memberEntity.setFamilyRelation(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.EDUCATION_LEVEL,memberEntity.getEducation());
            memberEntity.setEducation(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.HEALTH,memberEntity.getHealthState());
            memberEntity.setHealthState(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.WORK_POWER,memberEntity.getWorkPower());
            memberEntity.setWorkPower(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.Employment_Status,memberEntity.getWorkState());
            memberEntity.setWorkState(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.CENSUS_TYPE,memberEntity.getCensusType());
            memberEntity.setCensusType(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.NATION,memberEntity.getNation());
            memberEntity.setNation(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.SERIOUS_DISEASE,memberEntity.getSeriousDisease());
            memberEntity.setSeriousDisease(taDictPo.getLabel());

            memberEntity.setSex(StringUtils.isBlank(memberEntity.getSex())?"":dictionaryReadService.getCodeCache(DictConstant.SEX,memberEntity.getSex()).getLabel());

            memberEntity.setIsdisability(StringUtils.isBlank(memberEntity.getDisabilityLevel())?"否":"是");

            memberEntity.setDisabilityLevel(StringUtils.isBlank(memberEntity.getDisabilityLevel())?"":dictionaryReadService.getCodeCache(DictConstant.DISABLED_LEVEL,memberEntity.getDisabilityLevel()).getLabel());

            memberEntity.setDisabilityType(StringUtils.isBlank(memberEntity.getDisabilityType())?"":dictionaryReadService.getCodeCache(DictConstant.DISABLE_TYPE,memberEntity.getDisabilityType()).getLabel());

            memberEntity.setIsHelpPoor(StringUtils.isBlank(memberEntity.getIsHelpPoor())?"":dictionaryReadService.getCodeCache(DictConstant.IS_HELP_POOR,memberEntity.getIsHelpPoor()).getLabel());

            memberEntity.setIsAtSchool(StringUtils.isBlank(memberEntity.getIsAtSchool())?"":dictionaryReadService.getCodeCache(DictConstant.IS_AT_SCHOOL,memberEntity.getIsAtSchool()).getLabel());

            memberEntity.setDocHelpPoor(StringUtils.isBlank(memberEntity.getDocHelpPoor())?"":dictionaryReadService.getCodeCache(DictConstant.DOC_HELP_POOR,memberEntity.getDocHelpPoor()).getLabel());

            memberEntity.setSelfcareLevel(StringUtils.isBlank(memberEntity.getSelfcareLevel())?"":dictionaryReadService.getCodeCache(DictConstant.SelfCareAbility,memberEntity.getSelfcareLevel()).getLabel());


            if(StringUtils.isNotBlank(memberEntity.getSelfcareSelect())){
                String[] splitSelect = memberEntity.getSelfcareSelect().split(",");
                StringBuffer sb = new StringBuffer();
                Arrays.asList(splitSelect).stream().forEach(splitString->sb.append(dictionaryReadService.getCodeCache(DictConstant.NEW_SELF,splitString).getLabel()).append(","));
                memberEntity.setSelfcareSelect(sb.toString().substring(0,sb.length()-1));
            }
            memberEntity.setState(StringUtils.isBlank(memberEntity.getState())?"":dictionaryReadService.getCodeCache(DictConstant.SURVIVAL_STATUS,memberEntity.getState()).getLabel());
        }

        for(FamilySupportEntity supportEntity:familySupportList){

            supportEntity.setSex(StringUtils.isBlank(supportEntity.getSex())?"":dictionaryReadService.getCodeCache(DictConstant.SEX,supportEntity.getSex()).getLabel());

            supportEntity.setSupportRelation(StringUtils.isBlank(supportEntity.getSupportRelation())?"":dictionaryReadService.getCodeCache(DictConstant.FM_RELATION,supportEntity.getSupportRelation()).getLabel());

            supportEntity.setSupportInfo(StringUtils.isBlank(supportEntity.getSupportInfo())?"":dictionaryReadService.getCodeCache(DictConstant.SUPPORT_INFO,supportEntity.getSupportInfo()).getLabel());
        }


        String uuid = UUIDUtils.getUUID();
        File tmpFile = new File(System.getProperty("java.io.tmpdir")+separator +uuid+".html");
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(htmlInputStream));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpFile)));
            String line = "";
            Gson gson = new GsonBuilder().serializeNulls().create();
            while((line=reader.readLine())!=null){
                writer.write(line);
                writer.newLine();
                if(line.indexOf("<script>")>1){

                    StringBuffer familyBuffer =  new StringBuffer();

                    familyBuffer.append("var familyInfo = ");
                    familyBuffer.append(gson.toJson(mainEntity));
                    writer.write(familyBuffer.toString());
                    writer.newLine();

                    writer.write("var memberDatas=");
                    writer.write(gson.toJson(familyMemberEntities));
                    writer.newLine();

                    writer.write("var supportDatas=");
                    writer.write(gson.toJson(familySupportList));
                    writer.newLine();

                    writer.write("var assetdatas=");
                    writer.write(gson.toJson(memberAssetsEntities));
                    writer.newLine();
                }
            }
            writer.close();
            reader.close();

            FileInputStream input = new FileInputStream(tmpFile);
            String objectKey = fileService.upload(input,tmpFile.getName());

            orderWriteService.updateBackUpFile(objectKey,orderId);

            tmpFile.delete();
            return objectKey;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1","备份发生异常");
        }
    }

    @Override
    public void verifyExpireCheck(String orderId){
        int count = checkReadService.selectExpireRecord(orderId);

        if(count<1){
            throw new BizException(FailureCode.ERR_20088);
        }
    }
    @Override
    public Map<String, String> gainBankInfo(BankAbutmentDTO dto, UserAccountVo userAccountVo) {
        Map<String, String> map = new HashMap<>();
        if(StringUtils.isEmpty(dto.getSsssidcardnum())){
            throw new BizException("-1","身份证号码不能为空");
        }
        if(StringUtils.isEmpty(dto.getSsssobjectname())){
            throw new BizException("-1","姓名不能为空");
        }
        if(StringUtils.isEmpty(dto.getBankcode())){
            throw new BizException("-1","开户银行不能为空");
        }
        if(StringUtils.isEmpty(dto.getAccouttype())){
            throw new BizException("-1","账号类型不能为空");
        }

        if(Constant.FundCapitalType.SOCIAL_SECURITY.equals(dto.getAccouttype())){
            dto.setAccouttype("0");
        }else{
            dto.setAccouttype("1");
        }


        String tenantIdStr = areaReadService.getTenantIdRela(userAccountVo.getOrgId().substring(0,6)+"000000");
        dto.setTenantId(tenantIdStr);

        String bankCode = bankMappingReadService.getFinanceByRescue(dto.getBankcode());
        dto.setBankcode(bankCode);
        dto.setDatasources("01");

        String result = fiscalAbutmentService.fiscalAbutmentInfo(dto);

        if(!StringUtils.isEmpty(result)){
            JSONObject jsonObject = JSONObject.parseObject(result);
            String code = jsonObject.getString("code");

            if("-1".equals(code)){
                throw new BizException("-1","当前补贴对象未绑定银行帐号");
            }else{
                String data = jsonObject.getString("data");
                JSONObject jsonData = JSONObject.parseArray(data).getJSONObject(0);
                String accountnum = jsonData.getString("accountnum");
                map.put("accountnum",accountnum);
            }
        }
        return map;
    }

    public void isCanEditOrder(String orderId, UserAccountVo userAccountVo){

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderId);

        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.ORDER_EDIT, orderStateVerifyDTO, userAccountVo);
    }

    @Override
    public void delete(FamilyMemberDTO dto, UserAccountVo accountVo){
        this.isCanEditOrder(dto.getOrderId(),accountVo);
        familyMemberWriteService.delete(dto,accountVo);
    }

    @Override
    public String addFamilyMember(FamilyMemberDTO dto,UserAccountVo accountVo){
        this.isCanEditOrder(dto.getOrderId(),accountVo);
        return  familyMemberWriteService.addFamilyMember(dto,accountVo);
    }

    @Override
    public void  updateFamilyMember(FamilyMemberDTO dto,UserAccountVo accountVo)  {
        if(Constant.DomesticRelation.ONESELF.equals(dto.getFamilyRelation()) && !Constant.PeopleState.NORMAL.equals(dto.getState())
                && checkifHasNormState(dto.getOrderId())){
            throw new BizException("-1","人员状态不为正常,与户主关系不能置为本人");
        }
        this.isCanEditOrder(dto.getOrderId(),accountVo);
        familyMemberWriteService.updateFamilyMember(dto,accountVo);
    }

    @Override
    public void updateFamilyMemberAssess(FamilyMemberDTO dto) {
        FamilyMemberEntity member = new FamilyMemberEntity();
        member.setId(dto.getId());
        member.setSelfcareSelect(dto.getSelfcareSelect());
        member.setSelfcareLevel(dto.getSelfcareLevel());
        familyMemberWriteService.updateFamilyMember(member);
    }

    @Override
    public void changeMemberApply(String familyId, String orderId, Map<String,String> relationshipMap,UserAccountVo accountVo){
        this.isCanEditOrder(orderId,accountVo);
        familyMemberWriteService.changeMemberApply(familyId,orderId,relationshipMap);
    }

    @Override
    public int houseHoldSuspend(String orderId,String familyId){

        int i = familyMemberWriteService.updateExpireByFamilyId(familyId);

        OrderEntity entity = new OrderEntity();
        entity.setOrderId(orderId);
        entity.setSaveMemberNumber(0);
        entity.setBaseSalary(0d);
        entity.setSalvMoney(0d);
        orderWriteService.updateIgnoreNull(entity);

        FamilyMainEntity familyMainEntity = new FamilyMainEntity();
        familyMainEntity.setId(familyId);
        familyMainEntity.setSaveMemberNumber(0);
        familyMainWriteService.updateFamily(familyMainEntity);

        familySalaryWriteService.deleteFamilySalaryByOrderId(orderId);
        return i;
    }


    private  boolean checkifHasNormState(String orderId) {
        boolean flag = false;

        List<FamilyMemberDTO> memberList = familyMemberReadService.listMemberByOrderId(orderId);
        for (FamilyMemberDTO member : memberList) {
            if (member.getState().equals(Constant.PeopleState.NORMAL)) {
                flag = true;
                break;
            }
        }
        return  flag;
    }

    @Override
    public void verifyOrderNoReason(String orderId){
        int i = orderReadService.selectOrderNoReason(orderId);
        if(i>0){
            throw new BizException("-1","复查原因为空，请在编辑页面填写复查原因。");
        }
    }
}
